package net.xdclass.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.OSSConfig;
import net.xdclass.service.FileService;
import net.xdclass.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 功能描述
 *
 * @author ASUS
 * @date 2024/07/11  21:17
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService {
    @Autowired
    private OSSConfig ossConfig;
    @Override
    public String uploadUserImage(MultipartFile file) {
        String bucketname = ossConfig.getBucketname();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        //获取oss客户端
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //获取文件的原始名xxx.jpg
        String filename = file.getOriginalFilename();
        //jdk8日期语法格式
        LocalDate now = LocalDate.now();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //   user/2024/07/11/sdsdwe/
        String folder = pattern.format(now);
        String extension = filename.substring(filename.lastIndexOf("."));


        //在oss上创建bucket文件夹
        String newFileName = CommonUtil.generateUUID();
        String path = "user/"+folder + "/" + newFileName + extension;

        try {
            PutObjectResult putObject = oss.putObject(bucketname, path, file.getInputStream());
            if(putObject != null){
                String imgUrl = "https://"+bucketname+"."+endpoint+"/"+path;
                return imgUrl;
            }
        } catch (IOException e) {
            log.info("文件上传失败：{}",e.getMessage());
        }finally {
            oss.shutdown();
        }
        return null;
    }
}
